package gui;

import gui.browse.Browse;
import gui.util.GUIUtils;
import gui.util.JFrameCadastro;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.text.MaskFormatter;

import model.Status;
import model.Usuario;

import com.jgoodies.forms.layout.CellConstraints;

import controller.PerifericoController;
import controller.UsuarioController;

public class UsuarioGUI extends JFrameCadastro {
	private static final long serialVersionUID = 1L;

	private JPanel panelCentral;
	
	private JTextField editCodigo;
	private JFormattedTextField editCpf;
	private JTextField editNome;
	private JTextField editEmail;
	private JPasswordField editSenha;
	private JTextField editProfissao;
	private JFormattedTextField editDataNascimento;
	
	private MaskFormatter maskCpf;
	private MaskFormatter maskData;
	private MaskFormatter maskCep;
	
	//Endereco
	private JTextField editLogradouro;
	private JTextField editNumero;
	private JTextField editCidade;
	private JFormattedTextField editCep;
	
	// Usuario
	private JTextField editNomeDependente;
	private JTextField editEmailDependente;
	private JComboBox comboStatus;
	
	private JButton botaoBrowse;
	
	public ActionListener actionIncluir;
	public ActionListener actionAlterar;
	public ActionListener actionExcluir;
	public ActionListener actionCancelar;
	public ActionListener actionGravar;
	
	public UsuarioGUI() {
		super();
		init();
	}

	public void init(){
		this.setTitle("Cadastro de Usuario");
	}

	public JPanel getPanelCentral() {
		if (panelCentral == null){
			panelCentral = new JPanel(GUIUtils.getLayout(15, 20));
			CellConstraints  cc = new CellConstraints();

			panelCentral.add(new JLabel("Codigo"),		cc.xywh(  2, 4,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(getEditCodigo(),			cc.xywh( 10, 4,  5, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCentral.add(getBotaoBrowse(),			cc.xywh( 16, 4,  2, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCentral.add(new JLabel("Nome"),		cc.xywh(  2, 6,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(getEditNome(),				cc.xywh( 10, 6, 23, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));
		
			panelCentral.add(new JLabel("CPF"),			cc.xywh(  2, 8,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(getEditCpf(),				cc.xywh( 10, 8,  8, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCentral.add(new JLabel("Data Nasc."),	cc.xywh( 20, 8,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(getEditDataNascimento(),	cc.xywh( 28, 8,  5, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));
			
			panelCentral.add(new JLabel("Email"),		cc.xywh(  2, 10,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(getEditEmail(),			cc.xywh( 10, 10, 23, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCentral.add(new JLabel("Senha"),		cc.xywh(  2, 12,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(getEditSenha(),			cc.xywh( 10, 12, 15, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCentral.add(new JLabel("Profiss�o"),	cc.xywh(  2, 14,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(getEditProfissao(),		cc.xywh( 10, 14, 15, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCentral.add(getLabelAlterado("Endere�o"),cc.xywh(  2, 16,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(new JSeparator(),			cc.xywh( 10, 16, 30, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));
			
			panelCentral.add(new JLabel("Logradouro"),	cc.xywh(  2, 18,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(getEditLogradouro(),		cc.xywh( 10, 18, 19, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCentral.add(new JLabel("Numero"),		cc.xywh( 30, 18, 5, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(getEditNumero(),			cc.xywh( 36, 18, 3, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCentral.add(new JLabel("Cidade"),		cc.xywh(  2, 20,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(getEditCidade(),			cc.xywh( 10, 20, 15, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCentral.add(new JLabel("Cep"),			cc.xywh( 26, 20,  5, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(getEditCep(),				cc.xywh( 32, 20,  7, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCentral.add(new JLabel("Status"),		cc.xywh(  2, 22,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(getComboStatus(),			cc.xywh( 10, 22,  8, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCentral.add(new JLabel("Dependentes"),	cc.xywh(  2, 24,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(new JSeparator(),			cc.xywh( 10, 24, 30, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));
			
			panelCentral.add(new JLabel("Nome"),		cc.xywh(  2, 26,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(getEditNomeDependente(),	cc.xywh( 10, 26, 23, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			panelCentral.add(new JLabel("Email"),		cc.xywh(  2, 28,  7, 1, CellConstraints.RIGHT, CellConstraints.DEFAULT ));
			panelCentral.add(getEditEmailDependente(),	cc.xywh( 10, 28, 23, 1, CellConstraints.FILL, CellConstraints.DEFAULT ));

			
		}
		return panelCentral;
	}
	private JLabel labelAlterado;
	public JLabel getLabelAlterado(String texto){
		if (labelAlterado == null){
			labelAlterado = new JLabel();
		}
		labelAlterado.setText(texto);
		labelAlterado.setFont(new Font(null, Font.BOLD, 11));
		return labelAlterado;
	}

	public JTextField getEditCodigo() {
		if (editCodigo == null){
			editCodigo = new JTextField();
			editCodigo.setEditable(false);
		}
		return editCodigo;
	}
	
	public JFormattedTextField getEditCpf() {
		if (editCpf == null){
			editCpf = new JFormattedTextField(getMaskCpf());
			editCpf.setEnabled(false);
		}
		return editCpf;
	}

	public JTextField getEditNome() {
		if (editNome == null){
			editNome = new JTextField();
			editNome.setEnabled(false);
		}
		return editNome;
	}

	public JTextField getEditEmail() {
		if (editEmail == null){
			editEmail = new JTextField();
			editEmail.setEnabled(false);
		}
		return editEmail;
	}

	public JPasswordField getEditSenha() {
		if (editSenha == null){
			editSenha = new JPasswordField();
			editSenha.setEnabled(false);
		}
		return editSenha;
	}

	public JTextField getEditProfissao() {
		if (editProfissao == null){
			editProfissao = new JTextField();
			editProfissao.setEnabled(false);
		}
		return editProfissao;
	}

	public JFormattedTextField getEditDataNascimento() {
		if (editDataNascimento == null){
			editDataNascimento = new JFormattedTextField(getMaskData());
			editDataNascimento.setEnabled(false);
		}
		return editDataNascimento;
	}

	public JTextField getEditLogradouro() {
		if (editLogradouro == null){
			editLogradouro = new JTextField();
			editLogradouro.setEnabled(false);
		}
		return editLogradouro;
	}

	public JTextField getEditNumero() {
		if (editNumero == null){
			editNumero = new JTextField();
			editNumero.setEnabled(false);
		}
		return editNumero;
	}
	
	public JTextField getEditCidade() {
		if (editCidade == null){
			editCidade = new JTextField();
			editCidade.setEnabled(false);
		}
		return editCidade;
	}
	
	public JFormattedTextField getEditCep() {
		if (editCep == null){
			editCep = new JFormattedTextField(getMaskCep());
			editCep.setEnabled(false);
		}
		return editCep;
	}

	public JTextField getEditEmailDependente() {
		if (editEmailDependente == null){
			editEmailDependente = new JTextField();
			editEmailDependente.setEnabled(false);
		}
		return editEmailDependente;
	}
	
	public JTextField getEditNomeDependente() {
		if (editNomeDependente == null){
			editNomeDependente = new JTextField();
			editNomeDependente.setEnabled(false);
		}
		return editNomeDependente;
	}
	
	public JComboBox getComboStatus() {
		if (comboStatus == null){
			comboStatus = new JComboBox(Status.values());
			comboStatus.setEnabled(false);
		}
		return comboStatus;
	}
	
	public JButton getBotaoBrowse(){
		return super.getBotaoBrowse(UsuarioController.getInstance());
	}


	public MaskFormatter getMaskCpf(){
		if (maskCpf == null){
			try {
				maskCpf = new MaskFormatter("###.###.###-##");
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return maskCpf;
	}
	
	public MaskFormatter getMaskCep() {
		if (maskCep == null){
			try {
				maskCep = new MaskFormatter("##.###-###");
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return maskCep;
	}
	
	public MaskFormatter getMaskData() {
		if (maskData == null){
			try {
				maskData = new MaskFormatter("##/##/####");
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return maskData;
	}
	
	@Override
	public ActionListener getActionIncluir() {
		if (actionIncluir == null){
			actionIncluir = new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					limparDados();
					escreverRegistro(true);
					getEditCodigo().setText("0");
				}
			};	
		}
		return actionIncluir;
	}

	@Override
	public ActionListener getActionAlterar() {
		if (actionAlterar == null){
			actionAlterar = new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					escreverRegistro(true);
				}
			};
		}
		return actionAlterar;
	}

	@Override
	public ActionListener getActionExcluir() {
		if (actionExcluir == null){
			actionExcluir = new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					if (getEditCodigo().getText() != null && !getEditCodigo().getText().trim().isEmpty()){
						try {
							int opcao = (JOptionPane.showConfirmDialog(null, "Tem certeza que deseja excluir o registro "+ getEditCodigo().getText() +"?",
									"T�tulo", JOptionPane.YES_NO_OPTION));
							if (opcao == JOptionPane.YES_OPTION) {
								UsuarioController.getInstance().excluirUsuario(Integer.valueOf(getEditCodigo().getText().trim()));
								limparDados();
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			};
		}
		return actionExcluir;
	}

	@Override
	public ActionListener getActionCancelar() {
		if (actionCancelar == null){
			actionCancelar = new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					limparDados();
					escreverRegistro(false);
				}
			};
		}
		return actionCancelar;
	}

	@Override
	public ActionListener getActionGravar() {
		if (actionGravar == null){
			actionGravar = new ActionListener() {
				@SuppressWarnings("deprecation")
				public void actionPerformed(ActionEvent arg0) {
					if (getEditCodigo().getText().trim() != null && !getEditCodigo().getText().trim().isEmpty()){
						if (getEditCodigo().getText().trim().equals("0")){
							try {
								UsuarioController.getInstance().inserirUsuario(
										getEditCpf().getText(),
										getEditNome().getText(),
										getEditEmail().getText(),
										getEditSenha().getText(),
										getEditProfissao().getText(),
										getEditDataNascimento().getText(),
										(Status)getComboStatus().getSelectedItem(),
										getEditNomeDependente().getText(),
										getEditEmailDependente().getText(),
										getEditLogradouro().getText(),
										getEditNumero().getText(),
										getEditCidade().getText(),
										getEditCep().getText());
							} catch (Exception e) {
								e.printStackTrace();
							}
						} else {
							try {
								UsuarioController.getInstance().alterarUsuario(
										Integer.valueOf(getEditCodigo().getText().trim()),
										getEditCpf().getText(),
										getEditNome().getText(),
										getEditEmail().getText(),
										getEditSenha().getText(),
										getEditProfissao().getText(),
										getEditDataNascimento().getText(),
										(Status)getComboStatus().getSelectedItem(),
										getEditNomeDependente().getText(),
										getEditEmailDependente().getText(),
										getEditLogradouro().getText(),
										getEditNumero().getText(),
										getEditCidade().getText(),
										getEditCep().getText());
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
					escreverRegistro(false);
					limparDados();
					getBotaoFechar().grabFocus();
				}
			};
		}
		return actionGravar;
	}

	
	public void limparDados(){
		getEditCodigo().setText("");
		getEditCpf().setText("");
		getEditNome().setText("");
		getEditEmail().setText("");
		getEditSenha().setText("");
		getEditProfissao().setText("");
		getEditDataNascimento().setText("");
		getEditLogradouro().setText("");
		getEditNumero().setText("");
		getEditCidade().setText("");
		getEditCep().setText("");
		getEditNomeDependente().setText("");
		getEditEmailDependente().setText("");
		getComboStatus().setSelectedIndex(0);
	}
	public void escreverRegistro(boolean b){
		getBotaoCancelar().setEnabled(b);
		getBotaoGravar().setEnabled(b);
		getBotaoIncluir().setEnabled(!b);
		getBotaoAlterar().setEnabled(!b);
		getBotaoExcluir().setEnabled(!b);
		getBotaoFechar().setEnabled(!b);
		getBotaoBrowse().setEnabled(!b);
		getEditCodigo().setEnabled(!b);
		getEditNome().setEnabled(b);
		getEditCpf().setEnabled(b);
		getEditEmail().setEnabled(b);
		getEditSenha().setEnabled(b);
		getEditProfissao().setEnabled(b);
		getEditDataNascimento().setEnabled(b);
		getEditLogradouro().setEnabled(b);
		getEditNumero().setEnabled(b);
		getEditCidade().setEnabled(b);
		getEditCep().setEnabled(b);
		getEditNomeDependente().setEnabled(b);
		getEditEmailDependente().setEnabled(b);
		getComboStatus().setEnabled(b);
		getEditNome().grabFocus();
	}

	@Override
	public void preencherCampos(HashMap<String, Object> dados) {
		Usuario user = null;
		try {
			user = UsuarioController.getInstance().buscarUsuarioPorId((Integer) dados.get("codigo"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		editCodigo.setText(String.valueOf(user.getId()));
		editNome.setText(user.getNome());
		editCpf.setText(user.getCpf());
		editEmail.setText(user.getEmail());
		editSenha.setText(user.getSenha());
		editProfissao.setText(user.getProfissao());
		

		editLogradouro.setText(user.getEndereco().getLogradouro());
		editNumero.setText(user.getEndereco().getNumero());
		editCidade.setText(user.getEndereco().getCidade());
		editCep.setText(user.getEndereco().getCep());
		
		comboStatus.setSelectedItem(user.getStatus());
		
		editNomeDependente.setText(user.getNomeDependente());
		editEmailDependente.setText(user.getEmailDependente());
		
		
	}
}
